<?php
/**
 * 两种查找算法
 * Auther: Feyman
 * Date: 2015/9/5
 * Time: 19:28
 */

/**
 * 顺序查找
 * @param $arrData
 * @param $val
 * @return int
 */
function normal_search($arrData,$val) {
    $len = count($arrData);
    if($len == 0) return -1;
    for($i = 0;$i < $len; $i++ ) {
        echo "find No.",$i + 1," value = ",$arrData[$i]," is = ",$val,"? <br/>";
        // 找到了
        if($arrData[$i] == $val) return $i;
    }
    return -1;
}

/**
 * 二分查找
 * @param $arrData
 * @param $val
 * @return int
 */
function binary_search($arrData,$val) {
    $len = count($arrData);
    if($len == 0) return -1;

    $start = 0;
    $end   = $len - 1;

    while($start <= $end) {
        $middle = intval(($start + $end)/2);
        echo "start = ",$start," end = ",$end," middle = ",$middle,"<br/>";
        if($arrData[$middle] == $val) {
            return $middle;
        } elseif ($arrData[$middle] > $val) {
            $end = $middle - 1 ;
        } elseif ($arrData[$middle] < $val) {
            $start = $middle + 1;
        }
    }
    return -1;
}